package  com.bdqn.util;
import com.bdqn.entity.OmsOrder;
import com.bdqn.entity.responseDate.order.OmsOrderItemDto;
import com.bdqn.entity.util.Constants;
import com.bdqn.service.OmsOrderItemService;
import com.bdqn.service.OmsOrderService;
import com.bdqn.service.PmsSkuService;
import com.bdqn.util.OrderDelayQueueConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 订单信息消费者
 */
@Component
public class OrderTaskReceiver{
    private Logger logger = LoggerFactory.getLogger(OrderTaskReceiver.class);

    @Autowired
    OmsOrderService omsOrderService;
    @Autowired
    OmsOrderItemService omsOrderItemService;
    @Autowired
    PmsSkuService pmsSkuService;

    @RabbitListener(queues = OrderDelayQueueConfig.DLX_ORDER_QUEUE_NAME)
    public void orderListener(Message message){
        logger.info("orderListener消费者接收---message:[{}]", new String(message.getBody()));
        String orderId = new String(message.getBody());

        OmsOrder omsOrder = omsOrderService.getById(orderId);
        //如果订单状态不是 支付成功
        if(!omsOrder.getOrderStatus().equals(Constants.Order.PayStatus.SUCCESS)){
            //1.更新订单信息
            omsOrder.setOrderStatus(Constants.Order.Status.TIMEOUT);
            omsOrderService.updateById(omsOrder);
            //2.回滚商品库存
            List<OmsOrderItemDto> omsOrderItemList = omsOrderItemService.selectOrderItemListByOrderId(orderId);
            for (OmsOrderItemDto omsOrderItemDto : omsOrderItemList) {
                pmsSkuService.rollbackInventory(omsOrderItemDto.getProductQuantity(), omsOrderItemDto.getSkuId());
            }
        }
    }

}